#include "my_thread_queue.h"

extern thread_queue sleepq;
extern thread_queue runq;
extern thread_queue deadq;

thread_queue create_queue(){
	thread_queue q=malloc(sizeof(struct __thread_queue));
	q->first=NULL;
	q->last=NULL;
	q->size=0;
	return q;
}

void delete_queue(thread_queue queue){
	while(queue->size){
		thread_t tmp=queue->last;
		queue->last=tmp->prev;
		free(tmp);
		(queue->size)--;
	}
}
void insert(thread_t i,thread_queue q){
	if (q==NULL)
		q=create_queue();
	if (q->first == NULL){
		q->first = i;
		q->last =NULL;
	}
	else if(!q->last){
		q->last=i;
		i->prev=q->first;
		i->next=NULL;
	}
	else if (q->last){
		q->last->next = i;
		i->prev=q->last;
		q->last=i;
		i->next = NULL;
	}
	q->size++;
}

void remove_thread(thread_t t,thread_queue queue){
	thread_t prev;
	thread_t curr;
	if(queue!=NULL) {
		prev = queue->first;
		curr = queue->first;
		while(curr!=queue->last)  {
			if(curr==t) {
				prev->next = curr->next;
				curr->next->prev=prev;
				// unlink thread
				curr = prev->next;
			}
			prev = curr;
			curr = curr->next;
		}
		queue->size++;
	}
}
int isempty(thread_queue queue) {
	return queue->size==0;
}

